package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//预约管理
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void add(List<OrderSetting> orderSettingList) {
        //遍历集合
        if (orderSettingList != null && orderSettingList.size() > 0) {
            for (OrderSetting orderSetting : orderSettingList) {
                //通过日期查询数据库判断数据库中是否已经存在此日期的数据，避免重复录入
                long count = orderSettingDao.findCountByDate(orderSetting.getOrderDate());
                //如果已经存在，就执行更新数据的操作
                if (count > 0) {
                    orderSettingDao.updateByDate(orderSetting);
                } else {
                    //不存在，就执行添加数据的操作
                    orderSettingDao.add(orderSetting);
                }

            }
        }
    }

    //查询预约信息
    @Override
    public List<Map> getOrderSettingByMonth(String date) { //格式为：2020-1
        //拼接出完整的日期查询范围
        String begin = date + "-1"; //2020-1-1
        //每个月最多31天，所以直接拼接31作为范围的末尾
        String end = date + "-31";//2020-1-31
        Map<String, String> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);
        //将查询结果封装为一个个map集合，和页面需要的数据相匹配
        List<Map> result = new ArrayList<>();
        ///*this.leftobj = [
        //                        { date: 1, number: 120, reservations: 1 },
        //                        { date: 3, number: 120, reservations: 1 }
        //                        ]
        if (list != null && list.size() > 0) {
            for (OrderSetting orderSetting : list) {
                Map m = new HashMap();
                m.put("date", orderSetting.getOrderDate().getDate());//获取数组日期（几日）
                m.put("number", orderSetting.getNumber());
                m.put("reservations", orderSetting.getReservations());
                result.add(m);
            }
        }
        return result;
    }

    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //根据日期查询，此日期是否已经存在预约设置信息
        long count = orderSettingDao.findCountByDate(orderSetting.getOrderDate());
        if (count > 0) {
            //当前日期存在预约设置，就执行更新操作
            orderSettingDao.updateByDate(orderSetting);
        }else {
            //当前日期不存在预约设置，就执行插入操作
            orderSettingDao.add(orderSetting);
        }
    }
}
